<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo">
        <el-form-item label="服务中心名称">
          <el-input v-model="searchInfo.name" placeholder="服务中心名称" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchInfo.phone" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="省/市/区（县）" prop="province">
          <geo :province="searchInfo.province" :city="searchInfo.city" :area="searchInfo.area" @update:province="val => searchInfo.province = val" @update:city="val => searchInfo.city = val" @update:area="val => searchInfo.area = val"></geo>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="createdRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openCreate">新增</el-button>
      </div>
      <!-- <el-table :data="tableData" row-key="ID"> -->
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
        >
        <el-table-column label="服务中心名称" prop="name" min-width="160" />
        <el-table-column label="创建者" min-width="140">
          <template #default="scope">{{ scope.row.creatorInfo?.nickName || '-' }}</template>
        </el-table-column>
        <el-table-column label="手机号" prop="phone" min-width="140" />
        <el-table-column align="left" label="省/市/区(县)" prop="province" width="240">
          <template #default="{row}">
            <geo disabled :province="row.province" :city="row.city" :area="row.area" @update:province="val => row.province = val" @update:city="val => row.city = val" @update:area="val => row.area = val"></geo>
          </template>
        </el-table-column>
        <el-table-column label="详细地址" prop="addr" min-width="220" />
        <el-table-column label="创建时间" min-width="180">
          <template #default="scope">{{ formatDateYmd(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column label="状态" min-width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="2" @change="() => toggleEnable(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" :min-width="appStore.operateMinWith" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewDetail(scope.row)">查看详情</el-button>
            <el-button type="primary" link @click="openEdit(scope.row)">变更</el-button>
            <el-button type="danger" link @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination :current-page="page" :page-size="pageSize" :page-sizes="[10, 30, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
    </div>

    <el-dialog v-model="editDialog" title="服务中心" width="600px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="form" ref="formRef" label-width="120px">
        <el-form-item v-if="dialogFlag==='create'" label="账号"><el-input v-model="form.userName" /></el-form-item>
        <el-form-item v-if="dialogFlag==='create'" label="密码"><el-input v-model="form.password" show-password /></el-form-item>
        <el-form-item v-if="dialogFlag==='create'" label="确认密码"><el-input v-model="form.confirmPassword" show-password /></el-form-item>
        <el-form-item label="服务中心名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="手机号"><el-input v-model="form.phone" /></el-form-item>
        <el-form-item label="省/市/区" prop="province">
          <geo :province="form.province" :city="form.city" :area="form.area" @update:province="val => form.province = val" @update:city="val => form.city = val" @update:area="val => form.area = val"></geo>
        </el-form-item>
        <el-form-item label="详细地址"><el-input v-model="form.addr" /></el-form-item>
        <el-form-item v-if="dialogFlag==='edit'" label="新密码"><el-input v-model="form.newPassword" show-password /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="form.enable" :active-value="1" :inactive-value="2" /></el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialog=false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="detailDialog" title="详情" width="600px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="detail" label-width="120px">
        <el-form-item label="服务中心名称"><el-input v-model="detail.name" disabled /></el-form-item>
        <el-form-item label="手机号"><el-input v-model="detail.phone" disabled /></el-form-item>
        <el-form-item label="省/市/区" prop="province">
          <geo disabled :province="detail.province" :city="detail.city" :area="detail.area" @update:province="val => detail.province = val" @update:city="val => detail.city = val" @update:area="val => detail.area = val"></geo>
        </el-form-item>
        <el-form-item label="详细地址"><el-input v-model="detail.addr" disabled /></el-form-item>
        <el-form-item label="创建者"><el-input :model-value="detail.creatorInfo?.nickName || '-'" disabled /></el-form-item>
        <el-form-item label="创建时间"><el-input :model-value="formatDateYmd(detail.CreatedAt)" disabled /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="detail.enable" :active-value="1" :inactive-value="2" disabled /></el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="detailDialog=false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { formatDateYmd } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '@/pinia'
import { 
  createServiceCenter, 
  updateServiceCenter, 
  toggleServiceCenterEnable, 
  deleteServiceCenter, 
  getCenterDetail,
  getCenterList,
} from '@/api/serviceCenter'
import geo from '@/components/geo/geo.vue'
defineOptions({ name: 'ServiceCenter' })
const appStore = useAppStore()

const searchInfo = ref({ name: '', phone: '', province: '', city: '', area: '', addr: '' })
const createdRange = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

const onSubmit = () => { page.value = 1; getTableData() }
const onReset = () => { searchInfo.value = { name: '', phone: '', province: '', city: '', area: '', addr: '' }; createdRange.value = []; getTableData() }
const handleSizeChange = (val) => { pageSize.value = val; getTableData() }
const handleCurrentChange = (val) => { page.value = val; getTableData() }

const getTableData = async () => {
  const req = { page: page.value, pageSize: pageSize.value, ...searchInfo.value }
  if (createdRange.value?.length === 2) { req.startCreatedAt = createdRange.value[0]; req.endCreatedAt = createdRange.value[1] }
  const res = await getCenterList(req)
  if (res.code === 0) { tableData.value = res.data.list; total.value = res.data.total; page.value = res.data.page; pageSize.value = res.data.pageSize }
}
getTableData()

const editDialog = ref(false)
const dialogFlag = ref('create')
const formRef = ref(null)
const form = ref({ ID: 0, userName: '', password: '', confirmPassword: '', name: '', phone: '', province: '', city: '', area: '', addr: '', newPassword: '', enable: 1 })
const detailDialog = ref(false)
const detail = ref({})

const openCreate = () => { dialogFlag.value = 'create'; form.value = { ID: 0, userName: '', password: '', confirmPassword: '', name: '', phone: '', province: '', city: '', area: '', addr: '', newPassword: '', enable: 1 }; editDialog.value = true }
const openEdit = (row) => { dialogFlag.value = 'edit'; form.value = { ...row, ID: row.ID, newPassword: '' }; editDialog.value = true }

const submit = async () => {
  let res
  if (dialogFlag.value === 'create') { res = await createServiceCenter(form.value) } else { res = await updateServiceCenter(form.value) }
  if (res.code === 0) { ElMessage.success(dialogFlag.value==='create' ? '创建成功' : '变更成功'); editDialog.value=false; getTableData() }
}

const toggleEnable = async (row) => {
  const res = await toggleServiceCenterEnable({ ID: row.ID, enable: row.enable })
  if (res.code === 0) { ElMessage.success(row.enable===1?'启用成功':'禁用成功') } else { ElMessage.error(res.msg || '更新失败') }
}

const viewDetail = async (row) => {
  const res = await getCenterDetail({ id: row.ID })
  if (res.code === 0) { detail.value = res.data.detail; detailDialog.value = true }
}

const deleteRow = async (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', { type: 'warning' }).then(async () => {
    const res = await deleteServiceCenter({ id: row.ID })
    if (res.code === 0) { ElMessage.success('删除成功'); getTableData() }
  })
}
</script>
